// Copyright (c) ZeroC, Inc.

using IceRpc.Features;
using IceRpc.Slice;
using System.Diagnostics;
using VisitorCenter;

namespace GreeterServer;

/// <summary>A Chatbot is an IceRPC service that implements Slice interface 'Greeter'.</summary>
[SliceService]
internal partial class Chatbot : IGreeterService
{
    public readonly CallBackConnection _callbackConnection;
    public CallBackProxy _callbackProxy;

    public Chatbot(CallBackConnection callBackConnection)
    {
        _callbackConnection = callBackConnection;
    }
    public async ValueTask<string> GreetAsync(string name, IFeatureCollection features, CancellationToken cancellationToken)
    {

        Console.WriteLine($"Dispatching greet request {{ name = '{name}' }}");
        InitCallbackProxy(features);
        var result = await _callbackProxy.TodoAsync("todo call back", cancellationToken: cancellationToken);

        return new($"Hello, {name}!");
    }

    public ValueTask<string> RegAsync(CallBackProxy callback, string msg, IFeatureCollection features, CancellationToken cancellationToken)
    {
        _callbackProxy.TodoAsync("to do aa", features, cancellationToken);

        return new($"ok reg:{msg}");
    }
    public void InitCallbackProxy(IFeatureCollection features)
    {
        IDispatchInformationFeature? dispatch = features.Get<IDispatchInformationFeature>();

        Debug.Assert(dispatch != null);

        _callbackConnection.SetInvoker(dispatch.ConnectionContext.Invoker);

        Debug.Assert(!_callbackConnection.isInit);
        _callbackProxy = new CallBackProxy(_callbackConnection);
    }
}
